package com.mune.gulimall.cart.web;

import com.mune.gulimall.cart.service.CartService;
import com.mune.gulimall.cart.vo.Cart;
import com.mune.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
  @Autowired
  private CartService cartService;

    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItem> currentUserCartItems(){
      return cartService.getUserCartItems();
    }

  @GetMapping("/cartList.html")
  public String cartPage(Model model) throws ExecutionException, InterruptedException {
    Cart cart = cartService.getCart();
    model.addAttribute("cart", cart);
    return "cartList";
  }

  @GetMapping("/addCart")
  public String addCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) {

    try {
      cartService.addCart(skuId, num);
      redirectAttributes.addAttribute("skuId", skuId);
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return "redirect:http://cart.gulimall.com/addToCartSuccessPage.html";
  }

  @GetMapping("/addToCartSuccessPage.html")
  public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model) {
    CartItem cartItem = cartService.getCartItemBySkuId(skuId);
    model.addAttribute("item", cartItem);
    return "success";
  }

  /**
   * 更新购物项选中状态
   *
   * @return
   */
  @GetMapping(value = "/checkItem")
  public String checkItem(@RequestParam(value = "skuId") Long skuId,
                          @RequestParam(value = "checked") Integer checked) {
    cartService.checkItem(skuId, checked);
    return "redirect:http://cart.gulimall.com/cartList.html";
  }

  /**
   * 更新购物项数量
   *
   * @return
   */
  @GetMapping(value = "/countItem")
  public String countItem(@RequestParam(value = "skuId") Long skuId,
                          @RequestParam(value = "num") Integer num) {
    cartService.updateItemCount(skuId, num);
    return "redirect:http://cart.gulimall.com/cartList.html";
  }

  /**
   * 删除购物项
   *
   * @return
   */
  @GetMapping(value = "/deleteItem")
  public String deleteItem(@RequestParam("skuId") Integer skuId) {
    cartService.deleteItem(skuId);
    return "redirect:http://cart.gulimall.com/cartList.html";
  }
}
